package com.yunxi.module.system.controller.admin.captcha;

import cn.hutool.core.util.StrUtil;
import com.xingyuv.captcha.model.common.ResponseModel;
import com.xingyuv.captcha.model.vo.CaptchaVO;
import com.xingyuv.captcha.service.CaptchaService;
import com.yunxi.framework.common.util.servlet.ServletUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.annotation.security.PermitAll;
import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 管理后台 - 验证码
 * </p>
 *
 * @author lidy
 * @since 2024-05-09
 */
@Tag(name = "管理后台 - 验证码")
@RestController("adminCaptchaController")
@RequestMapping("/system/captcha")
public class CaptchaController {

    private static final Logger log = LoggerFactory.getLogger(CaptchaController.class);
    @Resource
    private CaptchaService captchaService;

    /**
     * 从 Request 请求中获取 ClientIP + UserAgent
     *
     * @param request 请求
     * @return ClientIP + UserAgent
     */
    public static String getRemoteId(HttpServletRequest request) {
        // 从请求中获取 IP
        String clientIP = ServletUtils.getClientIP(request);
        String userAgent = request.getHeader("user-agent");
        if (StrUtil.isNotBlank(clientIP)) {
            return clientIP + userAgent;
        }
        return request.getRemoteAddr() + userAgent;
    }

    @PostMapping("/get")
    @Operation(summary = "获得验证码")
    @PermitAll
    public ResponseModel get(@RequestBody CaptchaVO captchaVO, HttpServletRequest request) {
        assert request.getRemoteHost() != null;
        captchaVO.setBrowserInfo(getRemoteId(request));
        return captchaService.get(captchaVO);
    }

    @PostMapping("/check")
    @Operation(summary = "校验验证码")
    @PermitAll
    public ResponseModel check(@RequestBody CaptchaVO captchaVO, HttpServletRequest request) {
        captchaVO.setBrowserInfo(getRemoteId(request));
        return captchaService.check(captchaVO);
    }

}
